package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

// 打开文件

func main() {
	//readFromFile()

	readFromFileByBufio()
	//readFromFileByIoUtil()
}

func readFromFile() {
	file, err := os.Open("F:/go-the-way-of-learning/day3/8file_read/demo.txt")
	if err != nil {
		fmt.Printf("open file faild, err:%v\n", err)
		return
	}
	defer file.Close()

	tmp := make([]byte, 128)
	for true {
		read, err2 := file.Read(tmp[:])
		if err == io.EOF {
			fmt.Println("读完了")
			return
		}
		if err2 != nil {
			fmt.Printf("read file faild, err:%v\n", err2)
			return
		}
		fmt.Printf("读了%d个字节\n", read)
		fmt.Println(string(tmp[:read]))
		if read < 128 {
			return
		}
	}
}

// 利用bufio这个包读取文件
func readFromFileByBufio() {
	file, err := os.Open("F:/go-the-way-of-learning/day3/8file_read/demo.txt")
	if err != nil {
		fmt.Printf("open file faild, err:%v\n", err)
		return
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	for true {
		line, err := reader.ReadString('\n') // 读到换行符
		if err == io.EOF {
			if len(line) != 0 {
				fmt.Println(line)
			}
			fmt.Println("读完了")
			break
		}
		if err != nil {
			fmt.Printf("read file faild, err:%v\n", err)
			return
		}
		fmt.Println(line)
	}
}

func readFromFileByIoUtil() {
	file, err := ioutil.ReadFile("F:/go-the-way-of-learning/day3/8file_read/demo.txt")
	if err != nil {
		fmt.Printf("read file faild, err:%v\n", err)
		return
	}
	fmt.Println(string(file))
}
